package xyz.prob.kun.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.text.SimpleDateFormat;

@Configuration
public class ResitConfiguration {

    @Bean
    public JsonMapper jsonMapper(){
        return JsonMapper.builder()
                // 忽略 transient 修饰的属性
                .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true)
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                //反序列化时,遇到未知属性会不会报错
                //true - 遇到没有的属性就报错 false - 没有的属性不会管，不会报错
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                //如果是空对象的时候,不抛异常
                .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
                //修改序列化后日期格式
               // .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                //.defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .build();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,JsonMapper jsonMapper) {
        // 我们为了开发方便直接使用<String,Object>泛型
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // String序列化的配置
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化
        template.setKeySerializer(stringRedisSerializer);
        // Hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);


        // 设置值的序列化器为Jackson2JsonRedisSerializer
        Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(jsonMapper,Object.class);
        // value采用Jackson2JsonRedisSerializer的序列化方式
        template.setValueSerializer(jsonSerializer);
        // Hash的value也采用jackson2JsonRedisSerializer的序列化方式
        template.setHashValueSerializer(jsonSerializer);
        template.afterPropertiesSet();
        return template;
    }





}
